package org.xiyu.yee.capemanage.network;

import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;
import net.minecraft.world.entity.player.Player;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.xiyu.yee.capemanage.Capemanage;
import org.xiyu.yee.capemanage.data.PlayerCapeData;
import org.xiyu.yee.capemanage.util.CapeManager;

import java.util.function.Supplier;
import java.io.File;

public class CapeUpdatePacket {
    private final String playerName;
    private final String capeName;

    public CapeUpdatePacket(String playerName, String capeName) {
        this.playerName = playerName;
        this.capeName = capeName;
    }

    public static void encode(CapeUpdatePacket packet, FriendlyByteBuf buffer) {
        buffer.writeUtf(packet.playerName);
        buffer.writeUtf(packet.capeName);
    }

    public static CapeUpdatePacket decode(FriendlyByteBuf buffer) {
        return new CapeUpdatePacket(buffer.readUtf(), buffer.readUtf());
    }

    @OnlyIn(Dist.CLIENT)
    public static void handle(CapeUpdatePacket packet, Supplier<NetworkEvent.Context> contextSupplier) {
        NetworkEvent.Context context = contextSupplier.get();
        context.enqueueWork(() -> {
            Minecraft minecraft = Minecraft.getInstance();
            if (minecraft.level != null) {
                // 保存披风数据到本地文件
                File capeFolder = Capemanage.getCapeFolder();
                File playerDataFile = new File(capeFolder, packet.playerName + ".json");
                PlayerCapeData capeData = new PlayerCapeData(packet.playerName, packet.capeName);
                CapeManager.saveCapeData(playerDataFile, capeData);
                
                // 更新玩家披风
                minecraft.level.players().stream()
                    .filter(p -> p.getName().getString().equals(packet.playerName))
                    .findFirst()
                    .ifPresent(player -> {
                        if (player instanceof AbstractClientPlayer) {
                            AbstractClientPlayer clientPlayer = (AbstractClientPlayer) player;
                            // 强制刷新玩家披风
                            clientPlayer.setPos(clientPlayer.getX(), clientPlayer.getY(), clientPlayer.getZ());
                            // 触发重新加载皮肤和披风
                            clientPlayer.getSkinTextureLocation();
                            // 刷新玩家显示名称
                            player.refreshDisplayName();
                        }
                    });
            }
        });
        context.setPacketHandled(true);
    }
} 